package top.tungsword.webconsole.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import top.tungsword.webconsole.biz.response.WebReturnInfo;
import top.tungsword.webconsole.biz.util.CookieUtil;
import top.tungsword.webconsole.manager.cache.EhcacheLoginService;
import top.tungsword.webconsole.util.JsonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import static top.tungsword.webconsole.biz.constant.Constants.LOGIN_SESSION_ID;

@Component
public class AuthorityInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private EhcacheLoginService ehcacheLoginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        HandlerMethod method = (HandlerMethod)handler;
        Authority authority = method.getMethodAnnotation(Authority.class);
        //过滤不需要登录的
        if(authority != null && authority.unLogin()){
            return super.preHandle(request, response, handler);
        }
        String sessionId=CookieUtil.getValue(request, LOGIN_SESSION_ID);
        //判断是否需要登录
        Object isLogin = ehcacheLoginService.get(sessionId);
        if(isLogin != null){
            return super.preHandle(request, response, handler);
        }

        //返回json数据
        ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
        if(responseBody != null){
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            WebReturnInfo<String> webReturnInfo = WebReturnInfo.FAIL;
            webReturnInfo.setMessage("用户未登录，请重新登录");
            out.println(JsonUtil.toJsonString(webReturnInfo));
            return false;
        }

        //未登录去到登录页面
        response.sendRedirect(request.getContextPath() + "/login");

        return false;
    }
}
